<?
class product{
	public $product_id,
		$product_info_id,
		$prd_price,
		$prd_price_tva,
		$prd_price_ht,
		$prd_proprice,
		$prd_proprice_tva,
		$prd_proprice_ht,
		$prd_priceachat,
		$prd_priceachat_tva,
		$prd_priceachat_ht,
		$prd_colisage,
		$prd_qty,
		$prd_weight,
		$prd_stock,
		$prd_active,
		$prd_link,
		$prd_date_public,
		$prd_refcode,
		$prd_model,
		$prd_name,
		$sub_title,
		$prd_color,
		$prd_type,
		$prd_description,
		$tag,
		$keywords,
		$prd_composition,
		$haut_gamme,
		$prd_rating,
		$prd_rate_commentaire,
		$pg_acc_article,
		$prd_counter,
		$prd_oldprice,
		$prd_ecotax,
		$prd_code_barre,
		$id_livraison,
		$prd_photo,
		$link_photo
		;
	
var $attribut=array(),$technic=array(),$price_extra=array();

var $category=array();// Array numeric
var $menu=array(),$menu_numeric,$link_cat_product;// Array nom et links
var $photo=array();// Array photo
var $packs=array();//package
var $associe=array();//associe
var $caractere=array();
var $reviews=array(); // comentaire
var $dirCache='cache/';// directory for Cache product
var $time_clear_cache='+1 hour';
	public function __construct($id=0) {
		if($id){
			$this->product_id=$id;
			//self::clear_cache();// have to delete after finish
			//if it can load cache ifnot exist we cache it 
			if(!self::load_cache()) return self::cache();
		}
		return $this;
	}
	private function load_cache(){
		
		if (!is_dir(FCPATH.$this->dirCache)) return false;
		$cacheFile=FCPATH.$this->dirCache.__CLASS__."_$this->product_id.txt";
		if(file_exists($cacheFile)){
			if(filemtime($cacheFile) + strtotime($this->time_clear_cache)< 2*strtotime("now")){ 
			 	self::clear_cache();
			 	self::cache();
				return $this;
			}
			$obj= unserialize(file_get_contents($cacheFile));
			foreach(get_object_vars($this) as $property=>$value){
				if(property_exists(__CLASS__,$property) and isset($obj->$property)) $this->$property=$obj->$property;
			}
			return $this;
		}
		return false;
	}
	private function clear_cache($type=''){
		
		if($type=='all'){
			foreach (glob(__CLASS__."*.txt") as $cacheFile) 
				unlink($cacheFile);
		}else{
			$cacheFile=FCPATH.$this->dirCache.__CLASS__."_$this->product_id.txt";
			if(file_exists($cacheFile))unlink($cacheFile);
		}
	}
	// serialize this object to file with name ObjectCache$id.txt
	//delete if it's timeover
    private function cache(){
    	if (!is_dir(FCPATH.$this->dirCache))mkdir(FCPATH.$this->dirCache);
			$cacheFile=FCPATH.$this->dirCache.__CLASS__."_$this->product_id.txt";
			self::fetch();
		if(!$fp=fopen($cacheFile,'w')) trigger_error('Error opening object file',E_USER_ERROR);
		if(!fwrite($fp,serialize($this))) trigger_error('Error writing data to object file',E_USER_ERROR);	
		fclose($fp);
			return $this;
    }
    
	function __sleep(){
        return array_keys(get_object_vars($this));
    }
	function fetch(){
		if(!$this->product_id) return false;
		$CI=get_instance();
		$CI->load->database();
		$query = $CI->db->select()->from('product')->where(array('product_id' => $this->product_id))->get();
		$rows=$query->result();
		
		if(!empty($rows)){
			$row=$rows[0];
			$this->product_info_id=$row->product_info_id;
			$this->prd_price=$row->prd_price;		
			$this->price=$row->prd_price;
			$this->prd_price_tva=$row->prd_price_tva;
			$this->prd_price_ht=$row->prd_price_ht;
			$this->prd_proprice=$row->prd_proprice;
			$this->prd_proprice_tva=$row->prd_proprice_tva;
			$this->prd_proprice_ht=$row->prd_proprice_ht;
			$this->prd_priceachat=$row->prd_priceachat;
			$this->prd_priceachat_tva=$row->prd_priceachat_tva;
			$this->prd_priceachat_ht=$row->prd_priceachat_ht;
			$this->prd_colisage=$row->prd_colisage;
			$this->prd_qty=$row->prd_qty;
			$this->prd_weight=$row->prd_weight;
			$this->prd_stock=$row->prd_stock;
			$this->prd_active=$row->prd_active;
			$this->prd_link=$row->prd_link;
			$this->prd_date_public=$row->prd_date_public;
			//prix vente prive
			
			$query = $CI->db->select('price')->
						from('vente_privee')->
						where(array('id_prod' =>$this->product_id,'date_end >'=>'now()'))->
						get();
			if($query->num_rows()){
				$rows=$query->result();
				$row=$rows[0];
				$this->prd_price=$row->price;	
			}
			$query = $CI->db->get_where('product_info', array('prd_id' => $this->product_info_id));
			$rows=$query->result();
			if(!empty($rows)){
				$row=$rows[0];
			
				$this->prd_refcode=stripslashes($row->prd_refcode);
				$this->prd_model=stripslashes($row->prd_model);
				$this->prd_name=stripslashes($row->prd_name);
				$this->sub_title=stripslashes($row->sub_title);
				$this->prd_color=$row->prd_color;
				$this->prd_type=$row->prd_type;
				
				$this->prd_description=stripslashes($row->prd_description);
				$this->prd_composition=$row->prd_composition;
				$this->haut_gamme=$row->haut_gamme;
				$this->prd_rating=$row->prd_rating;
				$this->prd_rate_commentaire=stripslashes($row->prd_rate_commentaire);
				$this->pg_acc_article=$row->pg_acc_article;
				$this->keywords=$row->keywords;
				$this->tag=$row->tag;
				$this->prd_counter=$row->prd_counter;
				$this->prd_oldprice=$row->prd_oldprice;
				$this->prd_ecotax=$row->prd_ecotax;
				$this->prd_code_barre=$row->prd_code_barre;
				$this->id_livraison=$row->id_livraison;
			}
			$query = $CI->db->get_where('product_info_livraison', array('livraison_id' => $this->id_livraison));
			$rows=$query->result();
			if(!empty($rows)){				
				$this->livraison=$rows[0]->time_order;
			
				$sql="SELECT `price_cost` FROM `cost_delivery`
				WHERE `id_country` = 'fr'
					AND ( $this->prd_weight
					BETWEEN `w_min`
					AND `w_max` )
				ORDER BY `price_cost` ASC
				LIMIT  1";
			
				$query = $CI->db->query($sql);
				$row=$query->result() ;
				$this->livraison_price=$row[0]->price_cost;
			}
		//Fetch photo
			$temp=0;
			$query = $CI->db->get_where('product_photo', array('product_id' => $this->product_id));
			foreach ($query->result() as $row){
				if($temp++==0){ 
					$this->prd_photo=$this->link_photo=trim($row->link_photo);
				}
				$this->photo[$row->id]=$row->link_photo;
			}
		// end Fetch photo
			unset($temp);	
		
		
		
		//Fetch category
		 $sql="SELECT * FROM `product_cat` WHERE `product_info_id`='$this->product_info_id'";
		$query =  $CI->db->query($sql);
		if($query->num_rows())
			foreach ($query->result() as $row){
				$cat=new category_admin;
				$this->category[$row->id_category]=$cat->get_name_category($row->id_category);
				$this->link_cat_product[]=$row->link;
			}// end while category
			
		// Fetch reviews
		$sql="SELECT * FROM `product_avis` WHERE `id_prd`='$this->product_info_id'";
		$query = $CI->db->query($sql);
		if ($query->num_rows() > 0)
			foreach ($query->result() as $row){
				$sql_user="SELECT `nom`,`prenom` FROM `client_contact` where `id`='{$row['id_user']}'";
				$result_user =$CI->db->query($sql_user);
				$row_user=$result_user->fetch_assoc();
				$this->reviews[$row['id']]=array($row_user['nom'].' '.$row_user['prenom'],$row['date'],$row['rating'],$row['avis']);
			}// end while reviews
			
		//Fetch prix extra
		$sql="SELECT * FROM `product_price_extra` WHERE `product_id`='$this->product_id' ORDER BY `min_qty` ASC";
		$query = $CI->db->query($sql);
		if ($query->num_rows() > 0)
			foreach ($query->result() as $row)
				$this->price_extra[$row->id]=array($row->min_qty,$row->price_extra);
		// end while prix extra
			
		//Fetch Caracteristique
		$sql="SELECT v.`value`,`name_attribute` FROM `product_attribute_value` v,`product_attribute` a WHERE v.att_id=`attrib_id` AND v.`product_id`='$this->product_id'";
		$query = $CI->db->query($sql);
		$prd_link='';
		if ($query->num_rows() > 0)
			foreach ($query->result() as $row){
				$this->attribut[$row->value]=$row->name_attribute;
				$prd_link.=$row->name_attribute.' ';
			}
		// end while Careteritique
		if(strlen($prd_link)>2){
			//$prd_link=vietconvert($prd_link);
			$this->prd_link=str_replace('.html',$prd_link.'.html',$this->prd_lien);
		}
		//Fetch Option Attribut Ex: Color=[red,white,pink]	
		
			
		//Fetch Associe
		$sql="SELECT * FROM `product_part` WHERE `id_prd_part`='$this->product_info_id' OR	`assoc_prd`='$this->product_info_id'";
		$query = $CI->db->query($sql);

		if ($query->num_rows() > 0)
			foreach ($query->result() as $row){
				array_push($this->associe,$row->id_prd_part,$row->assoc_prd);
			}// end while  Associe
		$this->associe=array_unique($this->associe);
		
		//Fetch Fiche Technique
		$sql="SELECT * FROM `product_caracteristique` WHERE `id_prd`='$this->product_info_id'";
		$query =  $CI->db->query($sql);
		if ($query->num_rows() > 0)
			foreach ($query->result() as $row){
				$this->technic[$row->id]=array('type'=>$row->prd_caracteristique_type,'name'=>$row->prd_caracteristique_nom);
			}// end while  Fiche Technique
		
		
		}//End if  result->num_rows
		
		
	}//END function fetch
	
	private function qtyPrice($qty){
		if(count($this->price_extra)){
			$i=0;
			foreach($this->price_extra as $value){
				if($i==0) if($qty<$value[0])return $this->prd_price;
				$i++;
				 if($qty>=$value[0] and $qty<=$value[1])return  $this->prd_price=$value[2];
			}
			return $this->prd_price=$value[2];
		}else{
			return $this->prd_price;
		}
	}
	public function create(){
		$CI=get_instance();
		$CI->load->database();
		$data = array(
			'prd_refcode'=>$this->prd_refcode ,
			'prd_model'=>$this->prd_model ,
			'prd_name'=>$this->prd_name ,
			'sub_title'=>$this->sub_title ,
			'prd_color'=>$this->prd_color ,
			'prd_type'=>$this->prd_type ,
			'prd_description'=>$this->prd_description ,
			'tag'=>$this->tag ,
			'keywords'=>$this->keywords ,
			'prd_composition'=>$this->prd_composition ,
			'haut_gamme'=>$this->haut_gamme ,
			'prd_rating'=>$this->prd_rating ,
			'prd_rate_commentaire'=>$this->prd_rate_commentaire ,
			'pg_acc_article'=>$this->pg_acc_article ,
			'prd_counter'=>$this->prd_counter ,
			'prd_oldprice'=>$this->prd_oldprice ,
			'prd_ecotax'=>$this->prd_ecotax ,
			'prd_code_barre'=>$this->prd_code_barre ,
			'id_livraison' =>$this->id_livraison
		);
		$CI->db->insert('product_info', $data);
		$this->product_info_id=$CI->db->insert_id();
		//category
		$this->category=array_unique($this->category);
		if(count($this->category))
			foreach($this->category as	$value){
				$cat=new category_admin;
				$fullLink=$cat->get_link_category($value).'/'.$this->prd_link;
				$data = array('product_info_id'=>$this->product_info_id,'id_category'=>$value,'link'=>$fullLink);
				$CI->db->insert('product_cat', $data);
			}
		if(count($this->technic))
			foreach($this->technic as $key=>$value){
				$data = array(
						'id_prd'=>$this->product_info_id,
						'prd_caracteristique_type'=>$key,
						'prd_caracteristique_nom'=>$value);
				if(trim($value))
					$CI->db->insert('product_caracteristique', $data);
			}
		
		if(count($this->associe))
			foreach($this->associe as	$value){
				$data = array('id_prd_part'=>$this->product_info_id,'assoc_prd'=>$value);
				$CI->db->insert('product_part', $data);
			}
			
			$data = array(
						'product_info_id'=>$this->product_info_id,
						'prd_price'=>$this->prd_price,
						'prd_price_tva'=>$this->prd_price_tva,
						'prd_price_ht'=>$this->prd_price_ht,
						'prd_proprice'=>$this->prd_proprice,
						'prd_proprice_tva'=>$this->prd_proprice_tva,
						'prd_proprice_ht'=>$this->prd_proprice_ht,
						'prd_priceachat'=>$this->prd_priceachat,
						'prd_priceachat_tva'=>$this->prd_priceachat_tva,
						'prd_priceachat_ht'=>$this->prd_priceachat_ht,
						'prd_colisage'=>$this->prd_colisage,
						'prd_qty'=>$this->prd_qty,
						'prd_weight'=>$this->prd_weight,
						'prd_stock'=>$this->prd_stock,
						'prd_active'=>$this->prd_active,
						'prd_link'=>$this->prd_link,
						'prd_date_public'=>$this->prd_date_public);
			$CI->db->insert('product', $data);

			$this->product_id=$CI->db->insert_id();
			
		if(count($this->attribut))
			foreach($this->attribut as $key=>$value){
				$data = array('product_id'=>$this->product_id,'att_id'=>$key,'assoc_prd'=>$value);
				if(trim($value))
					$CI->db->insert('product_attribute_value', $data);
			}
			
		if(count($this->photo))
			foreach($this->photo as	$value){
				$data = array('product_id'=>$this->product_id,'link_photo'=>$value);
				if(trim($value))
					$CI->db->insert('product_photo', $data);
			}
			
		$this->price_extra=array_unique($this->price_extra);
		if(count($this->price_extra))
			foreach($this->price_extra as	$min_qty=>$value){
				$data = array('product_id'=>$this->product_id,'min_qty'=>$min_qty,'price_extra'=>$value);
				if(trim($value))
					$CI->db->insert('product_price_extra', $data);
			}	
		//indexation
		$indexation=new indexation($this->product_info_id,$this->prd_name ,5);
		$indexation->save(true);
		if(trim($this->prd_description)){
			$indexation->chaine=$this->prd_description;
			$indexation->poids=2;
			$indexation->save(true);
		}
		if(trim($this->keywords)){
			$indexation->chaine=$this->keywords;
			$indexation->poids=2;
			$indexation->save(true);
		}
		
		return $this->product_id;
	}
	function edit_description(){
		global $mysqli;
		/* Delette old version Indexation */
		$sql="DELETE FROM `product_word` WHERE `id` IN (
					select `id_mot` FROM `index_word` 
					where `id_mot` not in (
							SELECT DISTINCT `id_mot` FROM `index_word` 
							where `id_doc`<>'$this->product_info_id') and `id_doc`='$this->product_info_id'
			)";
		$mysqli->query($sql);
		$sql="DELETE FROM  `index_word` WHERE `id_doc`='$this->product_info_id'";
		$mysqli->query($sql);
		/* END of del old version*/
		$description=addslashes($this->strips_description());
		$sql = "UPDATE  `product_info` SET `prd_description` = '$description' WHERE  `prd_id` = '$this->product_info_id'";
		$mysqli->query($sql);
		
		$this->indexation();
	}
	
	

	//Edit product
	
	function edit(){
		
		if(trim($_POST['prd_description'])!=''){
			$this->prd_description= $_POST['prd_description'];
			$this->edit_description();
		}
		foreach($_POST as $key=>$value){
			list($name,$temp)=explode('_',$key);
			if($name=='cat')$cat[]=$value;
			
			if($name=='TypeChar')$TypeCaracter[$temp]=$value;
			if($name=='DetailChar') 
				if(trim($value)=='')unset($TypeCaracter[$temp]);
				else $DetailCaracter[$temp]=$value;
			
			if($name=='att')$att[$temp]=$value;
			if($name=='attValue') 
				if(trim($value)=='') unset($att[$temp]);
				else $attValue[$temp]=$value;
			
			if($name=='priceExtra') 
				if(trim($value)=='') unset($priceExtra[$temp]);
				else $priceExtra[$temp]=array($_POST['qtyMin_'.$temp],$_POST['qtyMax_'.$temp],$value);		
		}
		
		if(isset($cat) )
			foreach($cat as $key=>$value){
				 $sql="INSERT INTO `product_cat` (
						`id_prd` ,
						`prd_categoryid` 
						)
						VALUES (
						'$this->product_id', '$value'
						);";
					$mysqli->query($sql);
			}
			
		$photo=explode(',',$_POST['photo_id']);
		if(count($photo))
			foreach($photo as $key=>$value) if($value=='')unset($photo[$key]);
		if(count($photo))
			foreach($photo as	$value){				
					 $sql="INSERT INTO `product_photo` (
						`product_id` ,
						`link_photo`
						)
						VALUES (
						 '$this->product_id', '$value '
						);
						";
					$mysqli->query($sql);
				}
			
		
		if(isset($TypeCaracter) and isset($DetailCaracter))
			foreach($TypeCaracter as $key=>$value){
					$prd_caracteristique_type=addslashes($value);
					$prd_caracteristique_nom=addslashes($DetailCaracter[$key]);
					 $sql="INSERT INTO `product_caracteristique` (
					`id_prd` ,
					`prd_caracteristique_type` ,
					`prd_caracteristique_nom` 
					)
					VALUES (
					'$this->product_info_id',
					'$prd_caracteristique_type',
					'$prd_caracteristique_nom'
					);";
					$mysqli->query($sql);
					
			}
		/*
		if(isset($att) and isset($attValue))
			foreach($att as $key=>$value){
				$this->attribut[$value]=$attValue[$key];
			}
		*/
		if(isset($priceExtra)){
				foreach($priceExtra as	$value){				
					 $sql="INSERT INTO `product_price_extra` (
						`product_id` ,
						`min_qty` ,
						`max_qty` ,
						`price_extra`
						)
						VALUES (
						'$this->product_id', '{$value[0]}', '{$value[1]}', '{$value[2]}');
						";
					$mysqli->query($sql);
				}	
		}
		//del cache
		
		$cacheFile=FCPATH.$this->dirCache.__CLASS__."_$this->product_id.txt";
		if(file_exists($cacheFile)) unlink($cacheFile);
		
	}




	//strip tags
	public function reg_escape( $str )
	{
		$conversions = array( "^" => "\^", "[" => "\[", "." => "\.", "$" => "\$", "{" => "\{", "*" => "\*", "(" => "\(", "\\" => "\\\\", "/" => "\/", "+" => "\+", ")" => "\)", "|" => "\|", "?" => "\?", "<" => "\<", ">" => "\>" );
		return strtr( $str, $conversions );
	}
	private $str		= '';
	private $del=array('class', 'id','onclick','onblur','onclick','ondblclick','onfocus','onkeydown','onkeypress','onkeyup','onmousedown','onmousemove','onmouseout','onmouseover','onmouseup');
	
	public function strips_description(){
		return $this->prd_description=$this->strips($this->prd_description);
	}
	private function strips( $str )
	{
		$this->str = $str;
		
		if( is_string( $str ) && strlen( $str ) > 0 )
		{
			$res = $this->findElements();
			if( is_string( $res ) )
				return $res;
			$nodes = $this->findAttributes( $res );
			$this->removeAttributes( $nodes );
		}
		
		return $this->str;
	}
	
	private function findElements()
	{
		
		# Create an array of elements with attributes
		$nodes = array();
		preg_match_all( "/<([^ !\/\>\n]+)([^>]*)>/i", $this->str, $elements );
		foreach( $elements[1] as $el_key => $element )
		{
			if( $elements[2][$el_key] )
			{
				$literal = $elements[0][$el_key];
				$element_name = $elements[1][$el_key];
				$attributes = $elements[2][$el_key];
				if( is_array( $this->ignore ) && !in_array( $element_name, $this->ignore ) )
					$nodes[] = array( 'literal' => $literal, 'name' => $element_name, 'attributes' => $attributes );
			}
		}
		
		# Return the XML if there were no attributes to remove
		if( !$nodes[0] )
			return $this->str;
		else
			return $nodes;
	}
	
	private function findAttributes( $nodes )
	{
		
		# Extract attributes
		foreach( $nodes as &$node )
		{
			preg_match_all( "/([^ =]+)\s*=\s*[\"|']{0,1}([^\"']*)[\"|']{0,1}/i", $node['attributes'], $attributes );
			if( $attributes[1] )
			{
				foreach( $attributes[1] as $att_key => $att )
				{
					$literal = $attributes[0][$att_key];
					$attribute_name = $attributes[1][$att_key];
					$value = $attributes[2][$att_key];
					$atts[] = array( 'literal' => $literal, 'name' => $attribute_name, 'value' => $value );
				}
			}
			else
				$node['attributes'] = null;
			
			$node['attributes'] = $atts;
			unset( $atts );
		}
		
		return $nodes;
	}
	
	private function removeAttributes( $nodes )
	{
		
		
		# Remove unwanted attributes
		foreach( $nodes as $node )
		{
			
			# Check if node has any attributes to be kept
			$node_name = $node['name'];
			$new_attributes = '';
			
			if( is_array( $node['attributes'] ) )
			{
				foreach( $node['attributes'] as $attribute )
				{
					if(  !in_array( $attribute['name'], $this->del )  )
						$attribute_keep[$attribute['name']] = $attribute['value'];
				}
			}
			$replacement = $this->createAttributes( $node['name'], $attribute_keep);
			$this->str = preg_replace( '/'. reg_escape( $node['literal'] ) .'/', $replacement, $this->str );
			unset($attribute_keep);
		}
		
	}
	
	private function createAttributes( $tag, $attribute_keep)
	{ 
	 $new_tag="<$tag ";
	 $att='';
		if(is_array($attribute_keep))
			foreach($attribute_keep as $key=>$value)
				$att.="$key=\"$value\" ";
		$new_tag.=$att.">";
		return $new_tag;
	}

}//End Class